package com.eagle.functioninterface;

import org.junit.Test;

import java.util.Objects;
import java.util.function.BiFunction;

/**
 * {@link BiFunction}函数式接口是把两个事物转成另一个事物。相当于数学中的: z=f(x,y)
 * @author qinlinsen
 */
public class BiFunctionTest8 {
    /**
     * 从下面可以看出compute这一个方法就可以实现数学的四则运算
     */
    @Test
    public void testBiFunction() {
        //z=f(x,y)=x+y 当x=1,y=2时
        final Integer resultOne = compute(1, 2, (x, y) -> x + y);
        System.out.println(String.format("resultOne=%s",resultOne));
        //z=f(x,y)=x+y 当x=3,y=5时
        final Integer resultTwo = compute(3, 5, (x, y) -> x + y);
        System.out.println(String.format("resultTwo=%s",resultTwo));

        //z=f(x,y)=x-y 当x=8,y=9时
        final Integer resultThree = compute(8, 9, (x, y) -> x - y);
        System.out.println(String.format("resultThree=%s",resultThree));

        //z=f(x,y)=x * y 当x=8,y=9时
        final Integer resultFour = compute(8, 9, (x, y) -> x * y);
        System.out.println(String.format("resultFour=%s",resultFour));

        //z=f(x,y)=x * y 当x=18,y=9时
        final Integer resultFive = compute(18, 9, (x, y) -> x / y);
        System.out.println(String.format("resultFive=%s",resultFive));
    }

    private <T, U, R> R compute(T x, U y, BiFunction<T, U, R> processor) {
        Objects.requireNonNull(x);
        Objects.requireNonNull(y);
        Objects.requireNonNull(processor);
        final R result = processor.apply(x, y);
        return result;
    }
}
